package com.CMS.client.datasource;

import java.util.List;

import com.CMS.client.ItemMenuService;
import com.CMS.client.ItemMenuServiceAsync;
import com.CMS.server.domain.ItemMenu;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.types.DSDataFormat;
import com.smartgwt.client.types.DSProtocol;
import com.smartgwt.client.types.FieldType;

public class ItemMenuLookupDataSource extends BaseDataSource{

	public ItemMenuLookupDataSource(){
		setDataProtocol(DSProtocol.CLIENTCUSTOM);
        setDataFormat(DSDataFormat.CUSTOM);
        setClientOnly(false);
        addField(new DataSourceField("key", FieldType.FLOAT, "Key", 50, true));
        addField(new DataSourceField("value", FieldType.TEXT, "Value", 50, true));
	}
	
	/*
	@Override
    protected Object transformRequest(DSRequest request) {
        final String requestId = request.getRequestId();
        final DSResponse response = new DSResponse();
        response.setAttribute("clientContext", request.getAttributeAsObject("clientContext"));
        response.setStatus(0);
        if (request.getOperationType() == DSOperationType.FETCH) {
        	ItemMenuServiceAsync rpc = GWT.create(ItemMenuService.class);
        	try {
				rpc.getItems(new AsyncCallback<List<ItemMenu>>() {

					@Override
					public void onFailure(Throwable caught) {
						response.setStatus(RPCResponse.STATUS_FAILURE);
						processResponse(requestId, response);
					}
					public void onSuccess(List<ItemMenu> result) {
						response.setTotalRows(result.size());
						ListGridRecord[] records = new ListGridRecord[result.size()];
						for(int i=0; i<result.size(); i++){
							ListGridRecord record = new ListGridRecord();
							record.setAttribute("key", result.get(i).getId());
							record.setAttribute("value", result.get(i).getDescription());
							records[i] = record;
						}
						response.setData(records);
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
        }
        processResponse(requestId, response);
        return request.getData();
    }*/

	@Override
	protected void executeFetch(final String requestId, DSRequest request,
			final DSResponse response) {
		
		final int startIndex = (request.getStartRow () < 0)?0:request.getStartRow ();
		final int endIndex = (request.getEndRow ()== null)?-1:request.getEndRow ();
		
		ItemMenuServiceAsync rpc = GWT.create(ItemMenuService.class);
		rpc.getItems(new AsyncCallback<List<ItemMenu>>() {
			
			@Override
			public void onSuccess(List<ItemMenu> result) {
				int size = result.size ();
                if (endIndex >= 0) {
                	if (endIndex < startIndex) {
                		size = 0;
                    }
                    else {
                        size = endIndex - startIndex + 1;
                    }
                }
                //Creamos los registros a devolver
				Record[] regs = new Record[result.size()];
				if (size > 0) {
					for (int i = 0; i < regs.length; i++) {
						Record record = new Record();
						copyValues(result.get(i), record);
						regs[i] = record;
					}
				}
				response.setData(regs);
				//IMPORTANTE: para que funcione el paginado debemos especificar
				//el total de registro del result set
				response.setTotalRows (result.size ());
				processResponse(requestId, response);
			}
			
			@Override
			public void onFailure(Throwable caught) {
				response.setStatus(RPCResponse.STATUS_FAILURE);
				processResponse(requestId, response);
			}
		});
	}

	@Override
	protected void executeAdd(String requestId, DSRequest request,
			DSResponse response) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void executeUpdate(String requestId, DSRequest request,
			DSResponse response) {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void executeRemove(String requestId, DSRequest request,
			DSResponse response) {
		// TODO Auto-generated method stub
		
	}
	
	private void copyValues(ItemMenu from, Record to) {
		to.setAttribute(getDescription(), from.getDescription());
		to.setAttribute(getId(), from.getId());
	}
}
